<?php

class myTools 
{
    public static function validateFeed( $sFeedURL ) {
        $sValidator = 'http://feedvalidator.org/check.cgi?url=';

        if( $sValidationResponse = @file_get_contents($sValidator . urlencode($sFeedURL)) ) {
            if( stristr( $sValidationResponse , 'This is a valid RSS feed' ) !== false ) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }


    public static function truncate_text($text, $length = 30, $truncate_string = '...', $truncate_lastspace = false) {
        if ($text == '') {
            return '';
        }

        if (mb_strlen($text) > $length) {
            $truncate_text = self::utf8_substr($text, 0, $length - mb_strlen($truncate_string));
            if ($truncate_lastspace) {
                $truncate_text = preg_replace('/\s+?(\S+)?$/', '', $truncate_text);
            }

            return $truncate_text.$truncate_string;
        }
        else {
            return $text;
        }
    }



    public static function validateEmail($email) {
        return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
    }

    public static function parseDictionaryFilename($word) {
        $out = ereg_replace("[^[:alpha:]]", "_", $word);
        return substr($out, 0 , 20).'.mp3';
    }

    public static function scaleImage(&$width, &$height, $to) {

        $hscale = $height / $to;
        $wscale = $width / $to;

        if (($hscale > 1) || ($wscale > 1)) {
            $scale = ($hscale > $wscale)?$hscale:$wscale;
        } else {
            $scale = 1;
        }

        $width = floor($width / $scale);
        $height= floor($height / $scale);

        return array($width, $height, $scale);
    }

    public static function cropThumbnail($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale) {
        $ext = myTools::getFileExtension($image);
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
        if ($ext == 'jpg') {
            $source = imagecreatefromjpeg($image);
        }else {
            $source = imagecreatefrompng($image);
        }

        $thumb_image_name = myTools::changeFileExtension($thumb_image_name, $ext, 'jpg');

        imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);

        imagejpeg($newImage, $thumb_image_name, 90);

        chmod($thumb_image_name, 0777);

        return $thumb_image_name;
    }

    public static function getFileName($fileName) {
        try {
            return substr($fileName, strrpos($fileName,'/')+1,strlen($fileName)-strrpos($fileName,'/'));
        }catch (Exception $e) {

        }
        return ;
    }

    public static function getFileExtension($fileName) {
        return strtolower(substr(strrchr($fileName, '.'), 1));
    }

    public static function changeFileExtension($fileName, $old_ext, $new_ext) {
        return str_replace(".".$old_ext, ".".$new_ext, $fileName);
    }

    public static function utf8_substr($str,$from,$len) {
        # utf8 substr
        return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                '$1',$str);
    }

    public static  function utf8_ucfirst($string) {
        return utf8_encode(ucfirst(utf8_decode($string)));
    }

    public static function utf8_strtolower($string) {
        return utf8_encode(strtolower(utf8_decode($string)));
    }

    public static function getCurrentUrl() {
        return (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    }

    public static function mb_strlen($t, $encoding = 'UTF-8') {
        /* --enable-mbstring */
        if (function_exists('mb_strlen')) {
            return mb_strlen($t, $encoding);
        }
        else {
            return strlen(utf8_decode($t));
        }
    }

    public static function resizeImage($body) {
        return preg_replace('/<img[^>]+src=(?:\'|")(.+?)(?:\'|")[^>]+(?:\/)?>/i', '<img alt=" " class="autoimgresize" src="\\1" />', $body);
    }

    public static function auto_link_image($text) {
        if (!function_exists("auto_image_tag")) {
            function auto_image_tag($src) {
                return $src[1].'<a href="http'.$src[3]."://".$src[4].$src[5].'" target="_blank" rel="nofollow"><img src="http'.$src[3]."://".$src[4].$src[5].'" class="autoimgresize" alt=""/></a>'.$src[6];
            }

        }

        $regex = '/
        (                          # leading text
          <\w+.*?>|                # leading HTML tag, or
          [^=!:\'"\/]|               # leading punctuation, or 
          ^                        # beginning of line
        )
        (
          (?:http(s)?:\/\/)|           # protocol spec, or
          (www\.)                # www.*
        )
        (
          [-\w]+                   # subdomain or domain
          (?:\.[-\w]+)*            # remaining subdomains or domain
          (?::\d+)?                # port
          (?:(?:\/(?:(?:[~\w\+%-]|(?:[,.;:][^\s$]))+)?)+(?i:\.(?:jpg|jpeg|gif|png))) # path
          (?:\?[\w\+%&=.;-]+)?     # query string
          (?:\#[\w\-]*)?           # trailing anchor
        )
        ([[:punct:]]|\s|<|$)       # trailing text
        /x';       

        return preg_replace_callback($regex, "auto_image_tag", $text);

    }

    public static function getSentences($str, $max_word_count = 30) {
        $sentences = explode('. ', strip_tags($str));
        $description = "";
        $counter = 0;

        foreach ($sentences as $sentence) {
            $words = explode(' ', $sentence);
            $counter += count($words);
            $description .= $sentence . '. ';
            if ($counter > $max_word_count) {
                return trim($description);
            }
        }

        return trim($description);
    }

    public static function scrap($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $html = curl_exec($ch);
        if (!$html) {
            $html = null;
        }

        return $html;
    }

    /**
     * strips stopword
     */
    public static function stopwordsToChar($text, $char) {
        $words = preg_split('/[^\pL_]/u', $text, -1, PREG_SPLIT_NO_EMPTY);

        $c = new Criteria();
        $c->add(StopwordPeer::NAME, $words, Criteria::IN);
        $c->addSelectColumn(StopwordPeer::NAME);
        $rs = StopwordPeer::doSelectRS($c);
        while ($rs->next()) {
            $word = $rs->getString(1);
            $text = preg_replace("/([^\pL_])({$word})([^\pL_])/ui", "\\1$char\\3", ' '.$text.' ');
            $text = preg_replace("/([^\pL_])({$word})([^\pL_])/ui", "\\1$char\\3", $text); # removes duplicate ones
        }
        return trim($text);
    }


    public static function getObjectIds($objects, $method="getId") {
        $ids = array();
        foreach ($objects as $object) {
            $ids[] = $object->$method();
        }
        return $ids;
    }


    public static function stripText($text) {
        $text = strtolower($text);

        // strip all non word chars
        $text = preg_replace('/\W/', ' ', $text);

        // replace all white space sections with a dash
        $text = preg_replace('/\ +/', '-', $text);

        // trim dashes
        $text = preg_replace('/\-$/', '', $text);
        $text = preg_replace('/^\-/', '', $text);

        return $text;
    }


    public static function longword_break($str, $word_width) {
        $new_str = '';
        $len = strlen($str);
        $temp_str = '';
        $seperator = ' ';
        $is_opened = false;
        for($i = 0; $i < $len; $i++) {
            //open
            if($str[$i] == '<') {
                $is_opened = true;
                $new_str .= wordwrap($temp_str, $word_width, $seperator, 1);
                ;
                $temp_str = '';
                $new_str .= '<';
                //close
            } else if ($str[$i] == '>') {
                $is_opened = false;
                $new_str .= '>';
            } else {
                if ($is_opened) {
                    $new_str .= $str[$i];
                } else {
                    if ($str[$i] == $seperator) {
                        $new_str .= $temp_str.$seperator;
                        $temp_str = '';
                    } else {
                        $temp_str .= $str[$i];
                    }
                }
            }
        }
        return $new_str;
    }


    public static function resizeImages($filename, $folder, $sizes=array()) {
        try {
            $ext = myTools::getFileExtension($filename);

            if(in_array($ext, array('jpg', 'jpeg', 'png', 'gif', 'JPG', 'JPEG', 'PNG', 'GIF'))) {
                $uploadDir = sfConfig::get('sf_upload_dir').'/'.$folder.'/';
                if (sizeof($sizes) && $filename && file_exists($uploadDir.$filename)) {
                    foreach ($sizes as $size) {						
                        $thumbnail = new sfThumbnail($size, null, true, false, 100);
                        $thumbnail->loadFile($uploadDir.$filename);
                        $thumbnail->save($uploadDir.$size."-".$filename);
                    }
                }
            } // not an image file
        }catch (Exception $e) {

        }

    }


    public static function logActivity($object, $objectType, $ownerType, $ownerId, $isPublic=1) {
        sfContext::getInstance()->getConfiguration()->loadHelpers('Url');

        $body = "";
        switch ($objectType) {
            case 'apartment_new' : $body = '<span>Шинэ орон сууц нэмлээ: </span><a href="'.$object->getUri().'">'.$object;
                break;
            //case 'apartment_edit' : $body = '<span>Орон сууцны мэдээллийг шинэчиллээ: </span><a href="'.$object->getUri().'">'.$object; break;
            case 'company_new' : $body = '<span>Байгууллага бүртгүүллээ: </span><a href="'.$object->getUri().'">'.$object;
                break;
            //case 'company_edit': $body = '<span>Байгууллагын мэдээллийг шинэчиллээ: </span><a href="'.$object->getUri().'">'.$object; break;
            case 'product_new' : $body = '<span>Бүтээгдэхүүн нэмлээ: </span><a href="'.$object->getUri().'">'.$object;
                break;
            //case 'product_edit': $body = '<span>Бүтээгдэхүүний мэдээллийг шинэчиллээ: </span><a href="'.$object->getUri().'">'.$object; break;
            case 'content_new' : $body = '<span>'.myConstants::getActivityTypeValue($object->getType()).' нэмлээ: </span><a href="'.url_for('content/show?id='.$object->getId()).'">'.$object;
                break;
            //case 'content_edit': $body = '<span>'.myConstants::getActivityTypeValue($object->getType()).' засварлалаа: </span><a href="'.url_for('content/show?id='.$object->getId()).'">'.$object; break;
            case 'registration': $body = '<a href="'.url_for('@profile?id='.$object->getId()).'">Барилга.MN-д шинээр бүртгүүллээ.';
                break;
            //case 'user_info'   : $body = '<a href="'.url_for('@profile?id='.$object->getId().'&tab=info').'">Хувийн мэдээллээ шинэчиллээ.'; break;
            //case 'user'        : $body = '<a href="'.url_for('@profile?id='.$object->getId().'&tab=photo').'">Өөрийн бүтээлийн цомгоо шинэчиллээ.'; break;
            //case 'user_avator' : $body = '<a href="'.url_for('@profile?id='.$object->getId()).'">Цээж зургаа шинэчиллээ.'; break;
            case 'comment'     : $body = '<span>Сэтгэгдэл бичив: </span><a href="'.url_for('content/show?id='.$object->getId()).'">'.$object;
                break;
        }

        if($body) {
            if(in_array($objectType, array('apartment', 'company', 'product', 'content', 'user'))) {
                $images = Doctrine::getTable('Image')->findByObject($objectType, $object->getId());
                if(sizeof($images)) $body .= '<br/>';
                $path = sfConfig::get('sf_upload_dir').'/'.$objectType.'/'.$object->getPath().'/';
                $folder = '/uploads/'.$objectType.'/'.$object->getPath().'/';
                foreach ($images as $image) {
                    if($image->getFilename() && file_exists($path.'80-'.$image->getFilename()))
                        $body .= '<img src="'.$folder.'80-'.$image->getFilename().'" style="max-width:30px;max-height:30px;float:left;margin:1px;" />';
                }
            }
            $body .= '</a>';

            Doctrine::getTable('Activity')->log($objectType, $object->getId(), $body, $ownerType, $ownerId, $isPublic);
        }

    }



    public static function mn_en($st) {
        $replacement = array(
                "й"=>"i","ц"=>"c","у"=>"u","к"=>"k","е"=>"e","н"=>"n",'ү'=>'u',
                "г"=>"g","ш"=>"sh","щ"=>"sh","з"=>"z","х"=>"x","ъ"=>"\'",'ө'=>'u',
                "ф"=>"f","ы"=>"i","в"=>"v","а"=>"a","п"=>"p","р"=>"r",
                "о"=>"o","л"=>"l","д"=>"d","ж"=>"zh","э"=>"ie","ё"=>"e",
                "я"=>"ya","ч"=>"ch","с"=>"c","м"=>"m","и"=>"i","т"=>"t",
                "ь"=>"\'","б"=>"b","ю"=>"yu","\""=>"\'","'"=>"\'",
                "Й"=>"I","Ц"=>"C","У"=>"U","К"=>"K","Е"=>"E","Н"=>"N",'Ү'=>'U',
                "Г"=>"G","Ш"=>"SH","Щ"=>"SH","З"=>"Z","Х"=>"X","Ъ"=>"\'",'Ө'=>'U',
                "Ф"=>"F","Ы"=>"I","В"=>"V","А"=>"A","П"=>"P","Р"=>"R",
                "О"=>"O","Л"=>"L","Д"=>"D","Ж"=>"ZH","Э"=>"IE","Ё"=>"E",
                "Я"=>"YA","Ч"=>"CH","С"=>"C","М"=>"M","И"=>"I","Т"=>"T",
                "Ь"=>"\'","Б"=>"B","Ю"=>"YU",
        );

        foreach($replacement as $i=>$u) {
            $st = mb_eregi_replace($i,$u,$st);
        }
        return $st;
    }


    // not used
    public static function mb_uppercase($word) {
        $cyr_lower_chars = array(
                'е','щ','ф','ц','у','ж','э',
                'н','г','ш','ү','з','к','ъ',
                'й','ы','б','ө','а','х','р',
                'о','л','д','п','я','ч','ё',
                'с','м','и','т','ь','в','ю',);

        $latin_lower_chars = array(
                'å','ù','ô','ö','ó','æ','ý',
                'í','ã','ø','¿','ç','ê','ú',
                'é','û','á','º','à','õ','ð',
                'î','ë','ä','ï','ÿ','÷','¸',
                'ñ','ì','è','ò','ü','â','þ',);

        $cyr_upper_chars = array(
                'Е','Щ','Ф','Ц','У','Ж','Э',
                'Н','Г','Ш','Ү','З','К','Ъ',
                'Й','Ы','Б','Ө','А','Х','Р',
                'О','Л','Д','П','Я','Ч','Ё',
                'С','М','И','Т','Ь','В','Ю',);

        $latin_upper_chars = array(
                'Å','Ù','Ô','Ö','Ó','Æ','Ý',
                'Í','Ã','Ø','¯','Ç','Ê','Ú',
                'É','Û','Á','ª','À','Õ','Ð',
                'Î','Ë','Ä','Ï','ß','×','¨',
                'Ñ','Ì','È','Ò','Ü','Â','Þ',);

        //replacing lower cyrillic
        $word = str_replace($latin_lower_chars, $cyr_lower_chars, $word);
        //replacing upper cyrillic
        $word = str_replace($latin_upper_chars, $cyr_upper_chars, $word);
        return $word;
    }


    public static function getColorByNumber($number) {
        switch ($number) {
            case 1:
                $code = '483D8B';
                break;
            case 2:
                $code = '7FFFD4';
                break;
            case 3:
                $code = '8A2BE2';
                break;
            case 4:
                $code = 'A52A2A';
                break;
            case 5:
                $code = '5F9EA0';
                break;
            case 6:
                $code = '6495ED';
                break;
            case 7:
                $code = 'DC143C';
                break;
            case 8:
                $code = '008B8B';
                break;
            case 9:
                $code = 'B8860B';
                break;
            case 10:
                $code = 'FAEBD7';
                break;
        }
        return $code;
    }
    

}

?>